/*
 * Copyright (c) 2009, Jan Pastor. All Rights Reserved.
 */

package sk.jp.commons.ui;

import java.awt.Component;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;

/**
 * {@link JList} and {@link JComboBox} cell renderer for items that are
 * subclass of {@link ListOption}, with value of type {@link JComponent} or String.
 * <p>If items have value of String, renders they using JLabel. In case of
 * JComponent instances (typically items may have value of JPanel that contains
 * other components (icon + text, ...)), renders they as is.
 * <p>Note that JList and JComboBox doesn't redirect mouse click events to its items.
 */
public class ListOptionCellRenderer implements ListCellRenderer {

    /**
     * See {@link ListCellRenderer#getListCellRendererComponent(JList, Object, int, boolean, boolean)}
     * for details.
     *
     * @throws ClassCastException if given <code>listModel</c> doesn't contains
     * instances of {@link ListOption}.
     */
    public Component getListCellRendererComponent(JList list, Object value,
                                                  int index, boolean isSelected,
                                                  boolean cellHasFocus) {
        ListOption option = (ListOption) value;
        JComponent c;
        if(option.getItemValue() instanceof JComponent){
            c = (JComponent) option.getItemValue();
        }else{
            c = new JLabel(option.getItemValue().toString());
        }
        if (isSelected) {
            c.setBackground(list.getSelectionBackground());
            c.setForeground(list.getSelectionForeground());
        } else {
            c.setBackground(list.getBackground());
            c.setForeground(list.getForeground());
        }
        c.setOpaque(true);
        return c;
    }
}
